package com.xxg.fileshand.net;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.xxg.fileshand.constant.Constant;

import java.io.IOException;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


public abstract class BaseSingleObserver<T> implements SingleObserver<BaseResponse<T>> {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onSuccess(BaseResponse<T> tBaseResponse) {
        int code = tBaseResponse.getCode();
        switch (code) {
            case Constant.Code.TimeStampError:
                onFail(tBaseResponse.getCode(), tBaseResponse.getMsg());
//                Timber.d("onNext: TimeStampError0");
                return;
            case Constant.Code.UnAuthorized:
//                Timber.d("onNext: UnAuthorized");
//                BaseUser.getInstance().setAccess_token("", MainApplication.getContext());
                onFail(tBaseResponse.getCode(), tBaseResponse.getMsg());
                return;
            case Constant.Code.OK:
//                if (tBaseResponse.isSuccess()) {
                onRespone(tBaseResponse.getData());
//                    return;
//                } else {
//                    Timber.d("onNext: 发生未知错误"+tBaseResponse.getMessage());
//                    onFail(0, "发生未知错误！"+tBaseResponse.getMessage());
//                }
                return;
            default:
                //失败
//                Timber.d("onNext: UnAuthorized");
                onFail(tBaseResponse.getCode(), tBaseResponse.getMsg());
                return;
        }
    }


    @Override
    public void onError(Throwable e) {
        String errorMsg;

        if (e instanceof IOException) {
            /** 没有网络 */
            errorMsg = "Please check your network status";
        } else if (e instanceof HttpException) {
            /** 网络异常，http 请求失败，即 http 状态码不在 [200, 300) 之间, such as: "server internal error". */
//            errorMsg = ((HttpException) e).response().message();
            errorMsg = e.getMessage();
        } else if (e instanceof Exception) {
            /** 网络正常，http 请求成功，服务器返回逻辑错误 */
            errorMsg = e.getMessage();
        } else {
            /** 其他未知错误 */
            errorMsg = !TextUtils.isEmpty(e.getMessage()) ? e.getMessage() : "unknown error";
        }
//        Timber.e("error:%s", errorMsg);
        onFail(0, errorMsg);
    }

    public abstract void onRespone(@Nullable T data);

    public abstract void onFail(int code, String msg);
}
